<?php
/**
 * Created by b17
 * 2/28/12 8:59 PM
 */

abstract class Task
{
    protected $_pidFile;

    protected $_pidFp;

    protected $_taskName;

    /**
     * @var Logger
     */
    private $_logger;

    public function __construct($pidFile, $taskName)
    {
        $this->_pidFile = $pidFile;

        $this->_taskName = $taskName;
        $this->_logger = Logger::getInstance();
    }

    public function run()
    {
        if (!file_exists($this->_pidFile)) {
            $this->_pidFp = fopen($this->_pidFile, 'w');
            $this->doTask();
        } else {
            $this->_log("Task {$this->_taskName} is already running.");
        }
    }

    protected function _log($message)
    {
        $this->_logger->log($message, $this->_taskName);
    }

    protected abstract function doTask();

    public function __destruct()
    {
        if ($this->_pidFp) {
            fclose($this->_pidFp);
            unlink($this->_pidFile);
        }
    }
}
